package leetcode.editor.cn.q1_300.q;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author qidi
 * @date 2021-11-18 17:14:02
 */
class Q0040_CombinationSumIi {

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        List<List<Integer>> res = new ArrayList<>();

        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            Arrays.sort(candidates);
            if (candidates[0] > target) return res;
            process(candidates, target, 0, new ArrayList<>(), 0);
            return res;
        }

        private void process(int[] candidates, int target, int i, List<Integer> cur, int sum) {
            if (sum == target) {
                res.add(new ArrayList<>(cur));
            } else if (sum > target) {
                return;
            } else {
                for (int j = i; j < candidates.length; j++) {
                    if (j > i && candidates[j] == candidates[j - 1]) {
                        continue;
                    }
                    cur.add(candidates[j]);
                    process(candidates, target, j + 1, cur, sum + candidates[j]);
                    cur.remove(cur.size() - 1);
                }
            }
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)


    public static void main(String[] args) {
        Solution solution = new Q0040_CombinationSumIi().new Solution();
        System.out.println(solution.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8));
    }
}